package com.lh.auth.service.impl;

import com.lh.auth.client.UserClient;
import com.lh.auth.conf.JwtProperties;
import com.lh.auth.pojo.UserInfo;
import com.lh.auth.service.IAuthService;
import com.lh.auth.utils.CookieUtils;
import com.lh.auth.utils.JwtUtils;
import com.lh.user.pojo.UserDo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liuhe
 * @date 2020/07/07
 */
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements IAuthService {

    @Value("${leyi.jwt.cookieName}")
    private String cookieName;

    private final UserClient userClient;
    private final JwtProperties jwtProperties;

    public AuthServiceImpl(UserClient userClient, JwtProperties jwtProperties) {
        this.userClient = userClient;
        this.jwtProperties = jwtProperties;
    }

    @Override
    public String authentication(String username, String password) {
        UserDo userDo = this.userClient.queryUser(username, password);
        if (null == userDo) {
            return null;
        }
        try {
            String token = JwtUtils.generateToken(new UserInfo(userDo.getId(), userDo.getUsername()), jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            return token;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public UserInfo verifyUserAndUpdateCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        String curCookieValue = null;
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (StringUtils.equals(jwtProperties.getCookieName(), name)) {
                curCookieValue = cookie.getValue();
                break;
            }
        }
        if (StringUtils.isBlank(curCookieValue)) {
            return null;
        }

        try {
            // 验证用户信息
            UserInfo infoFromToken = JwtUtils.getInfoFromToken(curCookieValue, jwtProperties.getPublicKey());
            // 更新cookie
            String cookieValue = JwtUtils.generateToken(infoFromToken, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), cookieValue, jwtProperties.getCookieMaxAge());
            return infoFromToken;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
